package YAPserver;

import java.net.DatagramPacket;
import java.util.concurrent.ConcurrentLinkedQueue;

import YAPenvironment.YAPconstant;
import YAPenvironment.YAPconstant.Command;
import YAPserver.logic.Game;

/**
 * If a game is started, this runnable object gets the state of the game and sends it to the clients.
 */
public class GameActualizer extends Thread {
	
	Game YAP;
	Lobby lobby;
	/**
	 * The class which gets the actual state of the game and sends it to the clients.
	 * @param playersInLobby
	 * @param YAP
	 * @param lobby
	 */
	public GameActualizer(ConcurrentLinkedQueue<ClientHandler> playersInLobby, Game YAP, Lobby lobby){
		this.YAP = YAP;
		this.lobby = lobby;
	}
	
	/**
	 * Gets the state of the playing field every C_FPS_LIMIT times
	 * and sends it to the clients in the lobby. 
	 */
	@Override
	public void run(){
		long timeBefore;
		long timeAfter;
		while(lobby.isStarted()){
			
			try{
				timeBefore = System.currentTimeMillis();
				String string=YAP.getObjectPos()+" ";  //ACHTUNGACHTUNGACHTUNG!!! PROVISORISCH, " " MUSS IN ENDGÜLTIGER VERSION ENTFERNT WERDEN
				byte[] data = string.getBytes();
				for(ClientHandler cH: lobby.getPlayers()){
					YAPserver.udpSocket.send(new DatagramPacket(
							data, data.length, cH.getSocket().getInetAddress(), cH.getUdpPort()
							));
				}
				timeAfter = System.currentTimeMillis();
				Thread.sleep(1000/(int)YAPconstant.C_FPS_LIMIT - (timeAfter-timeBefore));
			}catch (Exception e){
				if(YAPconstant.C_DEBUG){ e.printStackTrace(); }
			}
		}
	}

	/**
	 * Sends the message to the client that the Playground needs to be rotated.
	 * @param rotate
	 */
	public void sendRotation(String rotate) {
		try{
			for(ClientHandler cH: lobby.getPlayers()){
				cH.writeMessage(Command.rotate + YAPconstant.C_SEPARATOR+rotate);
			}
		}catch (Exception e){
			
		}
	}
	/**
	 * Sends the status (number of lives) of a player to the specified client.
	 * @param playerStat status of a player in game
	 * @param id id of the player in game which corresponds to the id of the client
	 */
	public void sendPlayerStat(String playerStat, int id) {
		try{
			for(ClientHandler cH: lobby.getPlayers()){
				if(cH.getGameId()==id){
					cH.writeMessage(Command.playerLostLife + YAPconstant.C_SEPARATOR + playerStat);
				}
			}
		}catch (Exception e){
			
		}
	}
	/**
	 * Sends the specified sound code to all clients.
	 * @param sound
	 */
	public void sendSound(int sound) {
		try{
			for(ClientHandler cH: lobby.getPlayers()){
				cH.writeMessage(Command.sendSound + YAPconstant.C_SEPARATOR+sound);
			}
		}catch (Exception e){
			
		}
	}

}
